<template>
  <div>
	  <h2>{{msg}}</h2>
	  <p>{{count}}</p>
	  <p>计算属性：{{doubleCounter}}</p>
	  <p ref="desc"></p>
  </div>
</template>

<script lang="ts">
import { ref, defineComponent, reactive, computed, onMounted,onUnmounted, toRefs, watch } from 'vue'
export default defineComponent({
  name: 'Test',
  setup(){
	 let {count,doubleCounter} = countObj();
	
	//单值响应式
	let msg = ref('我是test组件');
	
	//使用元素引用
	const desc = ref(null);
	
	//侦听器
	watch(count,(val,oldVal) => {
		const p = desc.value;
		p.textContent = `count change from ${oldVal} to ${val}`
	})
	
	return {count,doubleCounter,msg,desc};
  }
})

function countObj():any {
	const data = reactive({
	  count:1,
	  doubleCounter: computed(() => data.count*2)
	});
	let timer:any;
	onMounted(()=>{
	  timer = setInterval(()=>{
		  data.count++;
	  },1000);
	})
	onUnmounted(()=>{
	  clearInterval(timer)
	})
	//return data; // => 外部使用 const data = countObj();  {{data.count}}
	return toRefs(data); //=> 外部使用 const {count,doubleCounter} = countObj();  {{count}},使用后，watch无法监听到
}
</script>

<style scoped>
a {
  color: #42b983;
}

label {
  margin: 0 0.5em;
  font-weight: bold;
}

code {
  background-color: #eee;
  padding: 2px 4px;
  border-radius: 4px;
  color: #304455;
}
</style>
